//
//  CZWelcomeViewController.swift
//  WeiBo
//
//  Created by Apple on 16/9/5.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//  微博appkey
let WeiBoAppKey = "932421745"
//  微博appsecret
let WeiBoAppSecret = "bf49771e565be773d40afb5de317dad0"
//  授权回调页
let WeiBoRedirect_Uri = "http://www.itcast.cn"

class CZOAuthViewController: UIViewController {

    // MARK:    --懒加载控件
    private lazy var webView = UIWebView()
    
    //  自定义登录页面视图
    override func loadView() {

        //  设置代理
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //  加载登录页面
        requestOAuthLogin()
        
    }
    //  第三方登录页面
    private func requestOAuthLogin() {
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiBoAppKey)&redirect_uri=\(WeiBoRedirect_Uri)"
        let urlRequest = URLRequest(url: URL(string: url)!)
        print(url)
        webView.loadRequest(urlRequest)
    }
    
    private func setupUI() {
        setupNavUI()
        title = "微博"
    }
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
    
    // MARK:    --点击事件
    @objc private func cancelAction() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillAction() {
    
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin123'")
    
    }
    
    //  代码抽取到viewModel
//    //  通过accesstoken获取用户信息
//    fileprivate func requestUserInfo(userAccount: CZUserAccount) {
//
//        CZNetworkTools.sharedTools.requestUserInfo(userAccount: userAccount) { (response, error) in
//            if error != nil {
//                print("网络加载异常: \(error)")
//                return
//            }
//            //  网络请求成功
//            guard let dic = response as? [String: Any] else {
//                print("不是一个正确的字典格式")
//                return
//            }
//            //  代码执行到此字典格式正确
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            //  归档用户对象
//            
//            let result = userAccount.saveUserAccount()
//            if result {
//                //  
//                print("用户保存成功，登录成功")
//            } else {
//                //  
//                print("用户归档失败")
//            }
//            
//        }
//        
////        let url = "https://api.weibo.com/2/users/show.json"
////        let params: [String : Any] = [
////            "access_token": userAccount.access_token!,
////            "uid": userAccount.uid
////        ]
////        
////        let urlPath = url + "?access_token=" + userAccount.access_token! + "&uid=\(userAccount.uid)"
////        print(urlPath)
////        
////        let sessionManager = AFHTTPSessionManager()
////        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        sessionManager.get(url, parameters: params, progress: nil, success: { (_, response) in
////            print(response)
////            }) { (_, error) in
////                print(error)
////        }
//        
//    
//    }
//    
//    //  获取accesstoken
//    fileprivate func requestAccesstoken(code: String) {
//        
//        //  使用网络封装类请求数据
//        CZNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//            if error  != nil {
//                print("网络请求异常")
//                return
//            }
//            //  代码执行到此网络请求成功
//            guard let dic = response as? [String: Any] else {
//                print("不是正确的字典格式")
//                return
//            }
//            
//            //  代码执行到此字典格式没有问题
//            let userAccount = CZUserAccount(dic: dic)
//            
//            //  通过token获取用户信息
//            //  函数调用必须使用self关键字
//            self.requestUserInfo(userAccount: userAccount)
//            
//        }
//        
//        
////        let url = "https://api.weibo.com/oauth2/access_token"
////        let params = [
////            "client_id": WeiBoAppKey,
////            "client_secret": WeiBoAppSecret,
////            "grant_type": "authorization_code",
////            "code": code,
////            "redirect_uri": WeiBoRedirect_Uri
////        ]
////        
////        let sessionManager = AFHTTPSessionManager()
////        //  添加可接受的类型
////        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        
////        sessionManager.post(url, parameters: params, progress: nil, success: { (_, response) in
////            
////            print(response)
////            }) { (_, error) in
////                print(error)
////        }
//        
//    }
    

    

}


// MARK:    --实现UIWebViewDelegate代理方法
extension CZOAuthViewController: UIWebViewDelegate {
    //  将要加载那个请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //  判断url是否为nil，为nil直接不用加载返回false
        guard let url = request.url else {
            return false
        }
        
        //  判断是否以回调页地址大头
        if !url.absoluteString.hasPrefix(WeiBoRedirect_Uri) {
            //  不是以回调页大头，加载页面
            return true
        }
        
        //  代码执行到此，是我们想要关系的数据，获取code
        if let query = url.query, query.hasPrefix("code=") {
            
            
            //  参数拿到后获取code
            if let range = query.range(of: "code=") {
                //  获取到返回后截取字符串
                //  通过截取光标位置获取到最后
                let code = query.substring(from: range.upperBound)
                //  获取accesstoken
//                requestAccesstoken(code: code)
                CZUserAccountViewModel.sharedUserAccount.requestAccesstoken(code: code, callBack: { (isSuccess) in
                    if isSuccess {
                        //  
                        print("登录成功")
                        //  切换根视图控制器到首页
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                        
                    } else {
                        print("登录失败")
                    }
                })
            }
            
            
            
        }
        
        
        
        return false
    }
    //  已经开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
}












